package com.bxji.spring.eurekaclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.bxji.spring.ms.commons.domain.User;

@RestController
public class ConsumerController {

    /**
     * RestTemplate是Spring提供的用于访问Rest服务的客户端，RestTemplate提供了多种便捷访问远程Http服务的方法，能够大大提高客户端的编写效率
     */
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 调用服务接口
     */
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id) {
        return this.restTemplate.getForObject("http://msec-provider-01/findById/" + id, User.class);
    }

    // 获取服务提供者的信息, 以验证负载配置
    @GetMapping("/getServerMeg")
    public String test() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("msec-provider-01");
        String result = "111" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":"
                + serviceInstance.getPort();
        System.out.println(result);

        return result;
    }

    // 调用运程服务接口
    @GetMapping("/sayHello")
    public String sayHello() {
        // 这个地址写注册服务名, 不区分大小写
        String result = this.restTemplate.getForObject("http://msec-provider-01/myinfo", String.class);
        return "通过服务调用返回结果 ：" + result;
    }

}
